<template>
  <transition name="vw-message-fade" @after-leave="handleAfterLeave">
    <div
      :class="['vw-message', type && !iconClass ? `vw-message--${type}` : '']"
      :style="positionStyle"
      v-show="visible"
    >
      <slot>
        <p class="vw-message__content">{{ message }}</p>
      </slot>
    </div>
  </transition>
</template>

<script>
  export default {
    data() {
      return {
        visible: false,
        message: '',
        duration: 3000,
        onClose: null,
        type: 'info',
        closed: false,
        verticalOffset: 20,
        iconClass: '',
        timer: null
      }
    },
    computed: {
      positionStyle() {
        // 控制当前组件的显示位置
        return {
          top: `${this.verticalOffset}px`
        }
      }
    },
    watch: {
      closed(newVal) {
        if (newVal) {
          this.visible = false
        }
      }
    },
    methods: {
      handleAfterLeave() {
        this.$destroy(true)
        this.$el.parentNode.removeChild(this.$el)
      },
      close() {
        this.closed = true
        if (typeof this.onClose === 'function') {
          this.onClose(this)
        }
      },
      clearTimer() {
        clearTimeout(this.timer)
      },
      startTimer() {
        if (this.duration > 0) {
          this.timer = setTimeout(() => {
            if (!this.closed) {
              this.close()
            }
          }, this.duration)
        }
      }
    },
    mounted() {
      this.startTimer()
    }
  }
</script>

<style lang="scss">
  @import './../../theme/src/message.scss';
</style>
